/*
 * @autor: Vânia Angelotti RA: 1430431112040
 */
package br.com.fiap.controller;

import br.com.fiap.model.Sac;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/pesquisar")
public class PesquisaController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        EntityManager manager = Persistence.createEntityManagerFactory("base").createEntityManager();

        Date dtInicio = new Date();
        Date dtFim = new Date();
        try {
            DateFormat df = DateFormat.getDateInstance(DateFormat.DATE_FIELD, new Locale("pt", "BR"));
            dtInicio = df.parse(req.getParameter("txtDataInicio"));
            dtFim = df.parse(req.getParameter("txtDataFim"));
        } catch (ParseException ex) {
            Logger.getLogger(CadastroSacController.class.getName()).log(Level.SEVERE, null, ex);
        }

        Query query = manager.createQuery("select s from Sac s where s.dtCriacao >= :dtInicio AND s.dtCriacao <= :dtFim");
        query.setParameter("dtInicio", dtInicio);
        query.setParameter("dtFim", dtFim);

        List<Sac> sacList = query.getResultList();
        req.setAttribute("sacList", sacList);
        req.getRequestDispatcher("/gerarRespostaPesquisa").forward(req, resp);
    }
}
